<!-- 理论视频 -->
<template>
  <div class="theoreticalVideo-page">
    <div class="pck-video">
      <div class="pck-video-l">
        <div class="pck-video-l-v">
          <video class="myVideo" ref="videoPlayer" @loadedmetadata="getDuration" @timeupdate="updateCurrentTime"
                 @play="playClick" @pause="pauseClick"
                 :src="baseInfo.video_link" controls controlslist="nodownload noplaybackrate"></video>
        </div>
        <div class="pck-video-l-title" v-if="baseInfo.title">
          <div class="pck-video-l-title-name">{{ baseInfo.title }}</div>
          <div class="pck-video-l-title-btn" @click="startAnsweringQuestions">开始答题</div>
        </div>
        <div class="pck-video-l-time" v-if="timeDuration">{{ timeDuration }}</div>
        <div class="pck-video-l-simple" v-html="baseInfo.abstract"></div>
      </div>
      <div class="pck-video-r">
        <div class="pck-video-r-box">
          <div class="pck-video-r-title">大纲</div>
          <div class="pck-video-r-con">
            <div style="margin-bottom: 20px">
              <el-tree
                  ref="tree"
                  :data="treeList"
                  :props="defaultProps"
                  :default-expanded-keys="defaultExpandedKeys"
                  node-key="id"
                  :render-content="renderContent"
                  @node-click="handleNodeClick">
              </el-tree>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getNestedData,
  getPracticalVideoDetail, getProgress,
  getSaveProgress,
  getSimulateDetail,
  getSimulatedExam,
  getStartAnswer
} from "@/api";

export default {
  name: "theoreticalVideo",
  data() {
    return {

      checkedNodeFontColor: '#FF0000', // 选中节点的字体颜色
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      defaultExpandedKeys: [],
      imgSrc: '',
      baseInfo: {},
      paperId: 0,
      courseId: null,
      id: null,
      timer: null,
      currentTime: 0, //当前播放时间
      duration: 0, // 视频总时长,
      progress: 0, // 当前播放进度
      timeDuration: 0, // 视频时长
    }
  },
  mounted() {
    this.getNestedData()
  },
  methods: {
    // 获取第一层最后一层节点
    getLastLevelKeys(nodes) {
      let keys = [];
      nodes.forEach(node => {
        if (node.children && node.children.length > 0) {
          keys = keys.concat(this.getLastLevelKeys(node.children));
        } else {
          keys.push(node); // 假设 label 就是 key，实际情况下可能需要根据实际情况调整
        }
      });
      return keys;
    },
    // 获取节点
    getNestedData() {
      getNestedData({ outline_type: 2 }).then(res => {
        if (res.code == 1) {
          if (res.data.length > 0) {
            this.treeList = res.data
            let node = this.getLastLevelKeys(this.treeList)[0];
            if (this.id) {
              this.defaultExpandedKeys = [this.id]
            } else {
              this.defaultExpandedKeys = [node.id]
              this.courseId = node.course_id
              this.paperId = node.paper_id
              this.id = node.id
            }
            if (this.courseId) {
              this.getDetail()
            }
          }
        }
      })
    },
    // 点击节点
    handleNodeClick (data, node) {
      // 如果当前节点是最后一级，则执行点击操作
      if (node.level == 3) {
        let params = {
          outline_id: data.id
        }
        this.id = data.id
        this.courseId = data.course_id
        this.paperId = data.paper_id
        if (this.courseId) {
          this.getDetail()
        }
      } else {
        // 如果不是最后一级，则阻止向上冒泡，不执行任何操作
        return false;
      }
    },

    renderContent(h, { node, data }) {
      if (node.level == 3) {
        return (
            <span>
              <i class="el-icon-document" style="margin-right: 4px;"></i>
              {data.title}
              <span style="margin-left: 10px">{(data.percentage* 100).toFixed(0)}%</span>

            </span>
        );
      } else {
        return (
            <span>
              <i class="el-icon-folder" style="margin-right: 4px;"></i> {node.label}
            </span>
        );
      }
    },

    // 获取详情
    getDetail() {
      let params = {
        course_id: this.courseId
      }
      getPracticalVideoDetail(params).then(res=> {
        if (res.code == 1) {
          this.baseInfo = res?.data?.detail || {}
          this.getProgress()
        }
      })
    },
    // 初始化获取视频总时长
    getDuration(e) {
      const video = this.$refs.videoPlayer;
      if (video) {
        let seconds = video.duration
        let hours = Math.floor(seconds / 3600);
        seconds %= 3600;
        let minutes = Math.floor(seconds / 60);
        seconds %= 60;
        let a = hours == 0 ? '00' : hours < 10 ? '0' + hours : hours
        let b = minutes == 0 ? '00' : minutes < 10 ? '0' + minutes : minutes
        let c = seconds.toFixed(0) == 0 ? '00' : seconds.toFixed(0) < 10 ? '0' + seconds.toFixed(0) : seconds.toFixed(0)
        this.timeDuration = `${a}:${b}:${c}`

      }
    },
    // 设置开始播放时间
    setStartTime(e) {
      const video = this.$refs.videoPlayer;
      if (video) {
        video.currentTime = e || 0
      }
    },
    // 获取当前播放进度
    updateCurrentTime() {
      const video = this.$refs.videoPlayer;
      if (video) {
        this.currentTime = video.currentTime;
        this.duration = video.duration; // 视频总时长
        if (this.duration) {
          this.progress = this.currentTime / this.duration
        }
      }
    },
    // 获取当前视频播放进度
    getProgress() {
      let params = {
        course_id: this.courseId,
        video_link: this.baseInfo.video_link
      }
      getProgress(params).then(res => {
        if (res.code == 1) {
          this.setStartTime(res.data)
        }
      })
    },
    // 保存播放进度
    getSaveProgress() {
      let params = {
        course_id: this.courseId,
        video_link: this.baseInfo.video_link,
        progress: this.progress.toFixed(2),
        video_seconds: this.currentTime.toFixed(0)
      }
      getSaveProgress(params).then(res => {
        if (res.code == 1) {
          this.getNestedData()
          // this.updateNodeTitle(this.id, this.progress.toFixed(2))
        }
      })

    },
    // 启动播放
    playClick(e) {
      this.getStartTime()
    },
    // 暂停播放
    pauseClick(e) {
      clearInterval(this.timer)
      this.getSaveProgress()
    },
    // 开启定时器
    getStartTime() {
      let that = this
      that.timer = setInterval(()=> {
        that.getSaveProgress()
      }, 10000)
    },
    // 开始答题
    startAnsweringQuestions() {
      if (!this.paperId) {
        this.$message.warning('该大纲下没有添加习题!')
        return
      }
      this.$router.push({
        path: '/theoreticalQuestion',
        query: {
          paper_id: this.paperId,
          id: this.id
        }
      })
    }

  },
  beforeDestroy() {
    // 在组件销毁前执行的代码
    clearInterval(this.timer)
    // 例如，你可以在这里取消订阅事件、清除计时器、或者清理其他资源
  }
}
</script>

<style lang="scss" scoped>
.theoreticalVideo-page {
  width: 100%;
  height: 100%;
  ::v-deep .el-tree .el-tree-node__content {
    padding:3px 0;
  }
  /* 覆盖被选中节点的字体颜色 */
  ::v-deep .el-tree .el-tree-node__content:hover {
    color: #409EFF; /* 更改为你想要的颜色 */
    background: rgba(229, 238, 255, 1);
  }
  ::v-deep .el-tree-node:focus>.el-tree-node__content {
    color: #409EFF!important;
    background: rgba(229, 238, 255, 1);
  }
}
</style>
